// snowEffect.js
let closeSnowEffect = null // 关闭方法
let isSnowEffectRunning = false // 标识特效是否正在运行

export const startSnowEffect = () => {
  // 如果特效已经在运行，直接返回
  if (isSnowEffectRunning) return

  isSnowEffectRunning = true // 设置标识为 true

  const cvs = document.createElement('canvas')
  const style = cvs.style
  style.position = 'fixed'
  style.left = 0
  style.top = 0
  style.width = '100%'
  style.height = '100%'
  style.pointerEvents = 'none' // 确保用户可以和页面其他部分交互
  style.zIndex = 99 // 设置 z-index

  document.body.appendChild(cvs)

  const ctx = cvs.getContext('2d')
  const { clientWidth: width, clientHeight: height } = document.documentElement
  cvs.width = width
  cvs.height = height

  // 创建固定数量的雪花
  const snowflakes = Array.from(new Array(400)).map(() => ({
    x: Math.random() * width,
    y: Math.random() * height,
    radius: Math.random() * 4 + 1,
    step: Math.random() * 1 + 1
  }))

  const render = () => {
    ctx.clearRect(0, 0, width, height)
    ctx.fillStyle = '#ffffff'

    snowflakes.forEach((snowflake) => {
      ctx.beginPath()
      ctx.arc(snowflake.x, snowflake.y, snowflake.radius, 0, Math.PI * 2)
      ctx.fill()

      // 雪花下落
      snowflake.y += snowflake.step
      if (snowflake.y > height) {
        snowflake.y = 0
        snowflake.x = Math.random() * width
      }
    })

    requestAnimationFrame(render)
  }

  render()

  // 定义关闭特效的方法
  closeSnowEffect = () => {
    if (cvs.parentNode) {
      document.body.removeChild(cvs) // 移除 canvas
    }
    isSnowEffectRunning = false // 重置标识
  }
}

// 导出关闭特效的方法
export const stopSnowEffect = () => {
  if (closeSnowEffect) {
    closeSnowEffect() // 调用关闭方法
    closeSnowEffect = null // 重置关闭方法
  }
}
